﻿using System.Collections;
using System.Windows.Forms;
using Nextensions.Text;

namespace Nextensions.GUI
{
	public class ListViewSorter : IComparer, ISorter
	{
		private int[] _columns;
		private SortOrder _sortOrder = SortOrder.None;

		public int Compare(object x, object y)
		{
			if(_columns == null)
				return 0;

			int result = 0;
			int column = 0;

			string t1, t2;
			int n1, n2;

			while(result == 0 && column < _columns.Length)
			{
				t1 = ((ListViewItem) x).SubItems[_columns[column]].Text;
				t2 = ((ListViewItem) y).SubItems[_columns[column]].Text;

				if(int.TryParse(t1, out n1) && int.TryParse(t2, out n2))
					result = n1.CompareTo(n2);
				else if(FileSize.IsValid(t1) && FileSize.IsValid(t2))
					result = FileSize.Compare(t1, t2);
				else
					result = string.Compare(t1, t2);

				column++;
			}

			if(SortOrder == SortOrder.Descending)
				result *= -1;

			return result;
		}

		public SortOrder SortOrder
		{
			get
			{
				return _sortOrder;
			}
			set
			{
				_sortOrder = value;
			}
		}

		public int[] SortingItemsIndexes
		{
			get
			{
				return _columns;
			}
			set
			{
				_columns = value;
			}
		}
	}
}